import WxRequest from 'mina-request'
import {getStorage,clearStorage} from './storage'
import { modal,toast} from './extendApi'
import {env} from './env'
// 对WxRequest进行实例化
const instance = new WxRequest({
  baseURL:env.baseURL,
  timeout:15000
})
// 配置请求拦截器
instance.interceptors.request = (config)=>{
  const token = getStorage('token')
  if(token){
    config.header['token'] = token
  }
  return config
}

// 配置响应拦截器
instance.interceptors.response = async(response)=>{
  const {isSuccess,data} =  response
  if(!isSuccess){
    wx.showToast({
      title: '网络异常',
      icon:'error'
    })
    return response
  }
  switch (data.code) {
    case 200:
      return data
    case 208:
      const res = await modal({
        content:'鉴权失败，请重新登录',
        showCancel:false
      })
      if(res){
        // 清除本地token
        clearStorage()
        wx.navigateTo({
          url: '/page/login/login',
        })
      }
      return Promise.reject(response)
  
    default:
      toast({
        title:'程序出现异常'
      })
      return Promise.reject(response)
  }
}
export default instance